<?php
/*======================================================================*\
|| #################################################################### ||
|| # Package - JBootstrap                								||
|| # Copyright (C) since 2007  Youjoomla LLC. All Rights Reserved.      ||
|| # license - PHP files are licensed under  GNU/GPL V2                 ||
|| # license - CSS  - JS - IMAGE files  are Copyrighted material        || 
|| # websites - http://www.youjoomla.com | http://www.yjsimplegrid.com  ||
|| #################################################################### ||
\*======================================================================*/

// no direct access 
if((int)JVERSION == 3){
	defined('JPATH_PLATFORM') or die;
}else{
	defined('_JEXEC') or die ('Restricted access');
}

// Initiate class to hold plugin events  
class plgSystemJBootstrap extends JPlugin{

	function plgSystemJBootstrap(&$subject, $config)
	{
		parent::__construct($subject, $config);
		$this->loadLanguage();
		global $plugin_dir;
		$plugin_dir = JPATH_SITE.DIRECTORY_SEPARATOR."plugins".DIRECTORY_SEPARATOR.'system'.DIRECTORY_SEPARATOR."JBootstrap".DIRECTORY_SEPARATOR;
	}
	
	/**
	 * add the bootstrap class
	 */
	public function onAfterRoute (){

		global $plugin_dir;
		$app = JFactory::getApplication();
		//include the bootstrap class
		if (!$app->isAdmin() && !class_exists('JHtmlBootstrap')){ 
			require_once $plugin_dir."lib".DIRECTORY_SEPARATOR."cms".DIRECTORY_SEPARATOR."html".DIRECTORY_SEPARATOR."jquery.php";
			require_once $plugin_dir."lib".DIRECTORY_SEPARATOR."cms".DIRECTORY_SEPARATOR."html".DIRECTORY_SEPARATOR."bootstrap.php";
		}	
	}

	/**
	 *recompile less files
	 */ 
	public function onBeforeCompileHead(){ 
		$app = JFactory::getApplication();
		jimport('joomla.filesystem.file');
		jimport('joomla.filesystem.folder');
		
		//run the compiler only if it's activated and app is not admin
		$document = JFactory::getDocument();
		$yjsg_check = JPATH_SITE.DIRECTORY_SEPARATOR."templates".DIRECTORY_SEPARATOR.$document->template.DIRECTORY_SEPARATOR."yjsgcore".DIRECTORY_SEPARATOR."lessc.inc.php";

		if(!$app->isAdmin() && $this->params->get('active', 0) == 1 && !JFile::exists($yjsg_check)){
			global $plugin_dir;
			

			
			// define default vars
			$lib_dir 			= $plugin_dir.DIRECTORY_SEPARATOR."lib".DIRECTORY_SEPARATOR;			
			$less_dir 			= JPATH_SITE.DIRECTORY_SEPARATOR."templates".DIRECTORY_SEPARATOR.$document->template.DIRECTORY_SEPARATOR."less".DIRECTORY_SEPARATOR;
			$input_less			= $less_dir.$this->params->get('input_file', 'template').".less";
			$output_folder		= $this->params->get('output_folder', 'css');
			$css_dir  			= JPATH_SITE.DIRECTORY_SEPARATOR."templates".DIRECTORY_SEPARATOR.$document->template.DIRECTORY_SEPARATOR.$output_folder.DIRECTORY_SEPARATOR;
			$output_css			= $css_dir.$this->params->get('output_file', 'template').".css";
			$compile_css		= $this->params->get('compile_css', 1);
			$compress_outcss	= $this->params->get('compress_outcss', 0);
			
			//check less folder and make sure there is no other less class
			if(!class_exists('lessc') && JFolder::exists($less_dir)){
				require_once "lib/lessc.inc.php";
				require_once "lib/lessphpcss.inc.php";
				require_once "lib/lessphpcache.inc.php";
			}
			
			//check less class and folder first 
			if(class_exists('lessPhpCss') && JFolder::exists($less_dir) && $compile_css == 1){
				$less 				= new lessPhpCss;
			}elseif(class_exists('lessPhpCache') && JFolder::exists($less_dir)){
				$less 				= new lessPhpCache;
			}
			
			// compress output 
			if($compress_outcss == 1){
				$less->setFormatter("compressed");
			}
			
				// load the cache
				$cacheFile = $lib_dir.'temp.php'; 
			
				if (file_exists($cacheFile)){
					include_once $cacheFile;
					$cache = unserialize($BSCache);
				} else {
					$cache = $input_less;
				}

				$newCache = $less->cachedCompile($cache);
				
				if (!is_array($cache) || $newCache["updated"] > $cache["updated"] || !file_exists($output_css)) {
					$less->compileFile($input_less,$output_css);
					$newCache['files'] = $less->allParsedFiles();
					$writeValue = "<?php defined('JPATH_PLATFORM') or die; \$BSCache = '".serialize($newCache)."'; ?>";
					file_put_contents($cacheFile, $writeValue);
				}			
		
		}
	}
	
	/**
	 * check to see if we have to restore backup files
	 */ 	
	public function onExtensionBeforeSave($name, &$data){
		global $plugin_dir;
		
		
		// clean cache on save 
		$lib_dir 			= $plugin_dir.DIRECTORY_SEPARATOR."lib".DIRECTORY_SEPARATOR;
		$cacheFile 			= $lib_dir.'temp.php';
		if(JFile::exists($cacheFile)) {
			JFile::delete($cacheFile);
		}
		
		$params 	= new JRegistry();
		if((int)JVERSION == 3){
			$params->loadString($data->params);
		}else{
			$params->loadJSON($data->params);
		}

		//restore all backup files
		if($params->get('restore_backup', 0) == 1){
			jimport('joomla.filesystem.file');
			jimport('joomla.filesystem.folder');
			
			//read all the backups files
			$restore_files = JFolder::files($plugin_dir."backups",".css");
			if(is_array($restore_files) && !empty($restore_files)){
			
				// Create a new query object.
				$db		= JFactory::getDbo();
				$query	= $db->getQuery(true);
		
				// Select the required fields from the table.
				$query->select('a.template');
				$query->from($db->quoteName('#__template_styles').' AS a');
				$query->where('a.home = 1');
				$query->where('a.client_id = 0');
				
				$db->setQuery($query);
				$default_template = $db->loadResult();		
		
				// Make sure there aren't any errors
				if ($db->getErrorNum()) {
					echo $db->getErrorMsg();
					exit;
				}
				$yjsg_check = JPATH_SITE.DIRECTORY_SEPARATOR."templates".DIRECTORY_SEPARATOR.$default_template.DIRECTORY_SEPARATOR."yjsgcore".DIRECTORY_SEPARATOR."lessc.inc.php";			
				if(!JFile::exists($yjsg_check)):
				foreach($restore_files as $file){
					//move the file back to the original location
					if($file != ""){
						$restore_path = str_replace("_dir_","/",$file);
						JFile::delete(JPATH_SITE.DIRECTORY_SEPARATOR."templates".DIRECTORY_SEPARATOR.$default_template.DIRECTORY_SEPARATOR.$restore_path);						
						if(JFile::copy($plugin_dir."backups".DIRECTORY_SEPARATOR.$file, JPATH_SITE.DIRECTORY_SEPARATOR."templates".DIRECTORY_SEPARATOR.$default_template.DIRECTORY_SEPARATOR.$restore_path)){
							$app = JFactory::getApplication();
							$app->enqueueMessage(JText::_('PLG_SYSTEM_JBOOTSTRAP_RESTORE_SUCCESSFULLY'));
						}
					}
				}
				endif;// end yjsg check
			}
			
			//put the restore param back to value 0, so we don't restore backup next time user saves the plugin
			$params->set('restore_backup', 0);
			$data->params = $params->__toString();
		}
		
		return true;
	}	
	
} // END CLASS